package cn.edu.hwec;
import com.zaxxer.hikari.*;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
public final class DBPool {
    private static final HikariDataSource DATA_SOURCE; 
    static {
        TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai")); //设置时区
        Properties prop = new Properties();
        HikariConfig cfg = new HikariConfig();
        try (InputStream is = DBHelper.class.getClassLoader().getResourceAsStream("db.properties")){
            prop.load(is);
            cfg.setDriverClassName(prop.getProperty("driver"));
            cfg.setJdbcUrl(prop.getProperty("url"));
            cfg.setUsername(prop.getProperty("user"));
            cfg.setPassword(prop.getProperty("pwd"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 连接池参数
        cfg.setMaximumPoolSize(5); //最大连接数
        cfg.setMinimumIdle(2); //最小空闲连接
        cfg.setConnectionTimeout(30000); //30秒超时
        cfg.setIdleTimeout(300000); //5分钟空闲回收
        cfg.setMaxLifetime(1800000); //30分钟最大生命周期
        //开启并优化 PreparedStatement 的缓存
        //缓存预编译的SQL语句，最多缓存250条，且只缓存长度在2048字符以内的SQL
        cfg.addDataSourceProperty("cachePrepStmts", "true");
        cfg.addDataSourceProperty("prepStmtCacheSize", "250");
        cfg.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        DATA_SOURCE = new HikariDataSource(cfg);
    }
    //防止外部实例化
    private DBPool() {}
    //获取连接
    private static Connection getConnection() throws SQLException {
        return DATA_SOURCE.getConnection();
    }
    //简化查询：返回 List<Map<String,Object>>
    public static List<Map<String, Object>> query(String sql, Object... params) throws SQLException{
        try (Connection conn = getConnection()) {
            return new QueryRunner().query(conn, sql, new MapListHandler(), params);
        }
    }
    //执行增删改的操作
    public static int update(String sql, Object... params) throws SQLException {
        try (Connection conn = getConnection()) {
            int rows = new QueryRunner().update(conn, sql, params);
            return rows;
        }
    }
    //关闭连接池（ServletContextListener 销毁时可调）
    public static void close() {
        if (DATA_SOURCE != null && !DATA_SOURCE.isClosed()) {
            DATA_SOURCE.close();
        }
    }
}
